package mviewer.renderer.software.core;

import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.Color;
import mviewer.renderer.software.interfaces.IBuffer;
import mviewer.types.Camera;

public class ZBuffer implements IBuffer {

	private float[][] buffer;
	private int width, height;
	private float zNear, zFar, cameraZ;

	public ZBuffer(int width, int height, Camera camera) {
		this.width  = width;
		this.height = height;
		cameraZ		= camera.getPosition().getZ();
		zNear		= camera.getZNear();
		zFar		= camera.getZFar();
		buffer		= new float[width][height];

		for (int i = 0; i < width; i++)
			for (int j = 0; j < height; j++)
				buffer[i][j] = zFar;
	}

	@Override
	public boolean displayPixel(int x, int y, float z) {
		z = cameraZ - z;

		if (z < zNear || z > zFar)
			return false;

		if (z < buffer[x][y]) {
			buffer[x][y] = z;
			return true;
		}
		return false;
	}

	@Override
	public int getWidth() {
		return width;
	}

	@Override
	public int getHeight() {
		return height;
	}

	@Override
	public BufferedImage renderImage() {
		BufferedImage res = new BufferedImage(buffer.length, buffer[0].length,
											  BufferedImage.TYPE_INT_RGB);
		Graphics2D g = res.createGraphics();

		for (int i = 0; i < buffer.length; i++)
			for (int j = 0; j < buffer[i].length; j++) {
				float brightness = 1 - (buffer[i][j] / zFar);
				g.setColor(new Color(brightness, brightness, brightness));
				g.drawLine(i, j, i, j);
			}
		return res;
	}
}
